let WebSocketServer = require("ws").Server;

wss = new WebSocketServer({
  port: 8181, // 端口号
});

let chatlist = "";

wss.broadcast = (msg) => {
  wss.clients.forEach((client) => {
    client.send(msg);
  });
};

// 连接成功
wss.on("connection", (ws) => {
  // 广播
  ws.on("message", (e) => {
    // 获取数据
    let resData = JSON.parse(e);

    chatlist = resData.chat;

    wss.broadcast(JSON.stringify({ chat: chatlist }));
  });

  // 关闭
  ws.on("close", () => {
    wss.broadcast(JSON.stringify({ chat: chatlist }));
  });
});
